import { defineStore } from 'pinia'
import axios from '@/utils/axios'
import { UserRoleMap } from '@/utils/enum'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: null,
    role: '',
  }),
  actions: {
    setToken(token) {
      this.token = token
      localStorage.setItem('token', token)
    },
    removeToken() {
      this.token = ''
      localStorage.removeItem('token')
    },
    async fetchUserInfo() {
      const res = await axios.get('/user/info')
      // 兼容所有角色
      if (res.studentInfo) {
        this.userInfo = { ...res.studentInfo, ...res.user }
        this.role = res.user?.role || 'STUDENT'
      } else if (res.enterpriseInfo) {
        this.userInfo = { ...res.enterpriseInfo, ...res.user }
        this.role = res.user?.role || 'ENTERPRISE'
      } else if (res.user) {
        this.userInfo = res.user
        this.role = res.user?.role || 'ADMIN'
      } else {
        this.userInfo = null
        this.role = ''
      }
    },
    logout() {
      this.removeToken()
      this.userInfo = null
      this.role = ''
    }
  }
}) 